<?php

namespace app\meizhuangapi\controller;

use app\meizhuangapi\model\Cart as CartModel;
use app\meizhuangapi\model\Order as OrderModel;
use app\meizhuangapi\service\order\Checkout as CheckoutModel;
use Throwable;
use think\Db;

use app\api\controller\Order as OrderCon;
/**
 * 订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends OrderCon
{
    protected $userDeal;
    /**
     * 收益余额
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function getUserDeal(){
        return db('dealer_user')->where('user_id',$this->user['user_id'])->find();
    }
    /**
     * 获取支付方式
     * @param $price
     * @return array
     */
    public function getPayType($price){
        $this->userDeal=$this->getUserDeal();
        $payType=[
            [
                'default_pay'=>0,
                'pay_status'=>0,
                'pay_type'=>10,
                'pay_name'=>'储值余额',
                'total_balance'=>$this->user['money'],
            ],
            [
                'default_pay'=>0,
                'pay_status'=>0,
                'pay_type'=>20,
                'pay_name'=>'收益余额',
                'total_balance'=>$this->userDeal['money'],
            ]
        ];
        foreach ($payType as $key=>$value){
            if ($this->user['default_pay']==10 && $value['pay_type']==10){
                $payType[$key]['default_pay']=1;
            }elseif($this->user['default_pay']==20 && $value['pay_type']==20){
                $payType[$key]['default_pay']=1;
            }

            if ($value['total_balance']>$price){
                $payType[$key]['pay_status']=1;
            }
        }
        return $this->renderSuccess($payType,'余额支付方式');
    }
    /**
     * 订单确认-立即购买
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function buyNow()
    {
        $this->log->setFilename('prepay/buynow');

        try{
            // 实例化结算台服务
            $Checkout = new CheckoutModel;
            // 订单结算api参数
            $params = $Checkout->setParam($this->getParam([
                'goods_id' => 0,
                'goods_num' => 0,
                'goods_sku_id' => '',
            ]));

            // 表单验证
            if (!$this->validate->scene('buyNow')->check($params)) {
                $this->log->error($this->validate->getError(), '表单验证失败');
                return $this->renderError($this->validate->getError());
            }

            // 立即购买：获取订单商品列表
            $model = new OrderModel;
            $goodsList = $model->getOrderGoodsListByNow(
                $params['goods_id'],
                $params['goods_sku_id'],
                $params['goods_num']
            );
            $assign_type=input('post.assign_type');
            //$assign_type=2;
            // 获取订单确认信息
            $orderInfo = $Checkout->onCheckout($this->user, $goodsList);

            if(bccomp($orderInfo['order_pay_price'], '5000', 2) == 1) {
                return $this->renderError('支付金额不能大于5000元');
            }

            //获取店铺头像，名称
            $storeInfo=Db::name('store_shop')->where(['wxapp_id'=>input('post.wxapp_id')])->find();
            //获取头像，资质图片
            $tx=Db::name('upload_file')->where(['file_id'=>$storeInfo['logo_image_id']])->find();
            //$zz=Db::name('upload_file')->where(['file_id'=>$storeInfo['image_id_yyzz']])->find();
            $storeInfo['headImageUrl']=$tx['file_url'].'/'.$tx['file_name'];
            if ($assign_type==1) {
                $orderInfo['storeInfo']=$storeInfo;
                return $this->renderSuccess($orderInfo);
            }

            $this->log->info('', '-----------------------------------------------------------------');
            $this->log->info('开始', '预下单');
            $this->log->info($params, '订单结算请求参数');
            $this->log->info(count($orderInfo['goods_list']), '即将创建的订单个数');
            $this->log->info('开始', '订单结算');
            // 订单结算提交

            if ($Checkout->hasError()) {
                $this->log->error($Checkout->getError(), '订单结算提交错误');
                return $this->renderError($Checkout->getError());
            }
            $this->log->info('完成', '订单结算提交');
            // 创建订单
            $this->log->info('开始', '创建订单');
            $orderInfo['wxapp_id']=input('post.wxapp_id');
            if (!$Checkout->createOrder($orderInfo)) {
                $this->log->error($Checkout->getError(), '订单创建失败');
                return $this->renderError($Checkout->getError() ?: '订单创建失败');
            }

            $this->log->info('结束', '创建订单');

            $this->log->info('开始', '构建微信支付请求');
            // 构建微信支付请求
            $payment = $model->onOrderPayment($this->user, $Checkout->model, $params['pay_type']);

            $this->log->info([
                'order_id' => $Checkout->model['order_id'],   // 订单id
                'pay_type' => $params['pay_type'],  // 支付方式
                'payment' => $payment               // 微信支付参数
            ], '构建微信支付请求');
            $this->log->info('结束', '返回微信预支付信息到前端');
            $this->log->info('结束', '预下单');
            // 返回结算信息

            return $this->renderSuccess([
                'order_id' => $Checkout->model['order_id'],   // 订单id
                'pay_type' => $params['pay_type'],  // 支付方式
                'payment' => $payment,               // 微信支付参数
                'pay_way'=>0,//余额支付方式0：微信支付  10：储蓄余额 20 收益余额
                'storeInfo'=>$storeInfo
            ], ['success' => '支付成功', 'error' => '订单未支付']);
        } catch(Throwable $t){
            $this->log->error(
                ['msg' => $t->getMessage(), 'file' => $t->getFile(), 'line' => $t->getLine(), 'code' => $t->getCode()],
                'buyNow抛出异常');
            return $this->renderError($t->getMessage());
        }
    }
    /**
     * 当面付支付
     * @param $price
     * @param $couponId
     * @param $message
     * @param $discount
     * @param $pay_way
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function payFace($price, $couponId, $message, $discount,$dis_type,$pay_type=10,$pay_way=0){
        if(bccomp($price, '5000', 2) == 1) {
            return $this->renderError('当面付金额不能大于5000元');
        }
        if(empty($price)) {
            return $this->renderError('请输入金额');
        }
        if($price<0.01) {
            return $this->renderError('输入的金额不正确');
        }
        $this->log->setFilename('prepay/payface');
        $this->log->info('', '-----------------------------------------------------------------');
        $this->log->info('开始', '预下单');
        try{
            // 实例化结算台服务
            // 立即购买：获取订单商品列表
            $model = new OrderModel;
            $orderInfo=[
                'user_id'=>$this->user['user_id'],
                'order_total_price'=>$price,
                'order_price'=>$price,
                'remark'=>$message,
                'pay_type'=>$pay_type,
                'pay_way'=>$pay_way,
                'dis_type'=>$dis_type,
            ];
            if ($dis_type==1){
                $orderInfo['coupon_id']=$couponId;
                $orderInfo['coupon_money']=$discount;
                $orderInfo['order_pay_price']=bcsub($price,$discount,2);
                $orderInfo['balance_money']=0;
                $orderInfo['balance_num']=0;
            }elseif($dis_type==2){
                $orderInfo['coupon_money']=0;
                $orderInfo['coupon_id']=0;
                $orderInfo['balance_money']=$discount;
                $orderInfo['balance_num']  =$discount;
                // 余额支付标记订单已支付
                $orderInfo['order_pay_price']=bcsub($price,$discount,2);
            }else{
                $orderInfo['coupon_money']=0;
                $orderInfo['coupon_id']=0;
                $orderInfo['balance_money']=0;
                $orderInfo['balance_num']  =0;
                $orderInfo['order_pay_price']=bcsub($price,$discount,2);
            }
            //余额支付，判断余额
            if($pay_type==10){
                $money=Db::name('dealer_user')->where(['user_id'=>$this->user['user_id']])->find();
                if (($this->user['money'] < $price)&&($money['money']<$price)) {
                    return $this->renderError('余额不足，无法使用余额支付');
                }
            }

            $this->log->info($orderInfo, '订单信息');
            $this->log->info('开始', '创建订单');
            $orderInfo['wxapp_id']=input('post.wxapp_id');
            // 创建订单
            if (!$model->createOrder($orderInfo)) {
                $this->log->info($model->getError(), '创建订单失败');
                return $this->renderError($model->getError() ?: '订单创建失败');
            }
            $this->log->info('成功', '创建订单');
            // 构建微信支付请求
            $payment = $model->onOrderPayment($this->user, $model ,$pay_type);
            $this->log->info('结束', '返回微信预支付信息到前端');
            $this->log->info('结束', '预下单');
            // 返回结算信息
            return $this->renderSuccess([
                'order_id' => $model['order_id'],   // 订单id
                'pay_type' =>$pay_type,  // 支付方式
                'payment' => $payment               // 微信支付参数
            ], ['success' => '支付成功', 'error' => '订单未支付']);
        }catch(\Throwable $t) {
            $this->log->error(
                ['msg' => $t->getMessage(), 'file' => $t->getFile(), 'line' => $t->getLine(), 'code' => $t->getCode()],
                'payFace抛出异常');
            return $this->renderError($t->getMessage());
        }
    }
    /**
     * 订单确认-购物车结算
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     */
    public function cart()
    {
        // 实例化结算台服务
        $Checkout = new CheckoutModel;
        // 订单结算api参数
        $params = $Checkout->setParam($this->getParam([
            'cart_ids' => '',
        ]));
        // 商品结算信息
        $CartModel = new CartModel($this->user);
        // 购物车商品列表
        $goodsList = $CartModel->getList($params['cart_ids']);
        // 获取订单结算信息
        $orderInfo = $Checkout->onCheckout($this->user, $goodsList);
        $assign_type=input('post.assign_type');
        //获取店铺头像，名称
        $storeInfo=Db::name('store_shop')->where(['wxapp_id'=>input('post.wxapp_id')])->find();
        //获取头像，资质图片
        $tx=Db::name('upload_file')->where(['file_id'=>$storeInfo['logo_image_id']])->find();
        //$zz=Db::name('upload_file')->where(['file_id'=>$storeInfo['image_id_yyzz']])->find();
        $storeInfo['headImageUrl']=$tx['file_url'].'/'.$tx['file_name'];
        $orderInfo['storeInfo']=$storeInfo;
        if ($assign_type==1) {
            return $this->renderSuccess($orderInfo);
        }
        // 创建订单
        $orderInfo['wxapp_id']=input('post.wxapp_id');
        if (!$Checkout->createOrder($orderInfo)) {
            return $this->renderError($Checkout->getError() ?: '订单创建失败');
        }
        // 移出购物车中已下单的商品
        $CartModel->clearAll($params['cart_ids']);
        // 构建微信支付请求
        $payment = $Checkout->onOrderPayment();
        // 返回状态
        return $this->renderSuccess([
            'order_id' => $Checkout->model['order_id'],   // 订单id
            'pay_type' => $params['pay_type'],  // 支付方式
            'payment' => $payment               // 微信支付参数
        ], ['success' => '支付成功', 'error' => '订单未支付']);
    }

    /**
     * 订单结算提交的参数
     * @param array $define
     * @return array
     */
    private function getParam($define = [])
    {
        return array_merge($define, $this->request->param());
    }

    /**
     *  余额支付
     * @param $orderId     订单id
     * @param $password    支付密码
     * @param $price       支付金额
     * @param $balanceType 余额支付方式 1，储值余额，2.收益余额
     */
    public function payBalance(){
        $orderId=input('post.orderId');
        $password=input('post.password');
        $price=input('post.price');
        $balanceType=input('post.balanceType');
        $model = new OrderModel;
        //更新订单pay_way
        if($balanceType==1){
            $pay_way=10;
        }else{
            $pay_way=20;
        }
        Db::name('order')->where(['order_id'=>$orderId])->update(['pay_way'=>$pay_way]);
        // 构建微信支付请求
        $order=Db::name('order')->where('order_id',$orderId)->find();
        $payment = $model->onOrderPaymentByBalance($this->user,$order,$password,$balanceType);
        // 返回结算信息
        return $this->renderSuccess([
            'order_id' => $orderId,   // 订单id
            'pay_type' => 10,  // 支付方式
            'payment'  => $payment               // 微信支付参数
        ], ['success'  => '支付成功', 'error' => '订单未支付']);
    }
}
